package com.marketlive.system.config.bundle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/*
(C) Copyright MarketLive. 2006. All rights reserved.
MarketLive is a trademark of MarketLive, Inc.
Warning: This computer program is protected by copyright law and international treaties.
Unauthorized reproduction or distribution of this program, or any portion of it, may result
in severe civil and criminal penalties, and will be prosecuted to the maximum extent
possible under the law.
*/

import org.marketlive.system.config.IConfigurationLeaf;
import com.marketlive.system.config.ConfigurationBranch;
import com.marketlive.system.config.ConfigurationLeaf;

import java.util.ResourceBundle;
import java.util.Enumeration;

/**
 * Loads resource bundles into ConfigurationLeaves.
 */
public class BundleLoader {

    /**
     * Logger
     */
    private static Log log = LogFactory.getLog(BundleLoader.class);

    /**
     * Loads the given <code>ResourceBundle</code> into the given <code>ConfigurationBranch</code>.
     * 
     * @param branch the <code>ConfigurationBranch</code> to load into 
     * @param bundle the <code>ResourceBundle</code> to load into the branch
     */
    public static void loadBundle( ConfigurationBranch branch, ResourceBundle bundle) {
        Enumeration e = bundle.getKeys();
        while (e.hasMoreElements()) {

            //todo:huw this needs to create subbranches if the key contains NODE_SEPERATORS
            String key = (String) e.nextElement();
            String path;
            String name;

            ConfigurationBranch subBranch;
            // get the branch, if required
            int seperatorPos = key.lastIndexOf(ConfigurationBranch.NODE_SEPARATOR);
            if (seperatorPos > 0) {
                // it belongs on a subbranch
                path = key.substring(0, seperatorPos);
                name = key.substring(seperatorPos+1);
                log.debug( "getting path: " + path );
                subBranch = (ConfigurationBranch) branch.getBranch( path, true);
            }
            else {
                // it belongs directly on this branch
                subBranch = branch;
                path = "";
                name = key;
            }

            // create the leaf
            String value = bundle.getString(key);
            IConfigurationLeaf leaf = new ConfigurationLeaf(name, value);

            // add the leaf
            subBranch.addLeaf(leaf);
        }
    }
}
